<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input{
            display: none;
        }
        button{
            background-color: skyblue;
            border-radius: 8px;
            height: 40px;
            line-height: 40px;
            width: 200px;
            border: transparent;
        }
    </style>
</head>
<body>
    <input type="file" accept="image/*">
    <button>选择文件</button>
    <img src="" alt="">

    <script>
        const btn = document.querySelector('button')
        const ipt = document.querySelector('input')
        const img = document.querySelector('img')
        btn.addEventListener('click', () => {
            ipt.click()
        })

        const api_avatar = 'http://ajax-api.itheima.net/api/file'
        ipt.addEventListener('change', () =>{ 
            // 怎么获取刚选中的img
            // const img = ipt.files[0]
            // console.log(img)

            // 这个img要放到哪里呢？FormData那个实例上
            const formdata = new FormData()
            formdata.append('avatar', ipt.files[0])

            fetch(api_avatar, {
                method:'POST',
                // headers:{
                //     'Content-Type': 'image/png'  ==> 和后端约定好要不要请求头
                // },
                body:formdata
            }).then(res => res.json()).then(res => {
                console.log(res)
                img.src = res.data.url
            })
        })
    </script>
</body>
</html>